// IndexedDB数据库配置
const DB_NAME = 'MemoDB';
const STORE_NAME = 'tasks';
const DB_VERSION = 1;

let db;

// 初始化数据库
function initDB() {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(DB_NAME, DB_VERSION);
    
    request.onerror = function(event) {
      console.error('数据库打开失败:', event.target.error);
      reject(event.target.error);
    };
    
    request.onsuccess = function(event) {
      db = event.target.result;
      console.log('数据库打开成功');
      resolve(db);
    };
    
    request.onupgradeneeded = function(event) {
      db = event.target.result;
      if (!db.objectStoreNames.contains(STORE_NAME)) {
        const objectStore = db.createObjectStore(STORE_NAME, { keyPath: 'id', autoIncrement: true });
        objectStore.createIndex('quadrant', 'quadrant', { unique: false });
        objectStore.createIndex('name', 'name', { unique: false });
        objectStore.createIndex('deadline', 'deadline', { unique: false });
        objectStore.createIndex('status', 'status', { unique: false });
        console.log('对象仓库创建成功');
      }
    };
  });
}

// 保存任务到数据库
function saveTask(task) {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction([STORE_NAME], 'readwrite');
    const objectStore = transaction.objectStore(STORE_NAME);
    
    const request = task.id ? 
      objectStore.put(task) : 
      objectStore.add(task);
    
    request.onsuccess = function(event) {
      task.id = event.target.result;
      resolve(task);
    };
    
    request.onerror = function(event) {
      reject(event.target.error);
    };
  });
}

// 获取所有任务
function getAllTasks() {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction([STORE_NAME], 'readonly');
    const objectStore = transaction.objectStore(STORE_NAME);
    
    const request = objectStore.getAll();
    
    request.onsuccess = function(event) {
      resolve(event.target.result);
    };
    
    request.onerror = function(event) {
      reject(event.target.error);
    };
  });
}

// 任务列表的删除方法（仅标记为已完成，不物理删除）
function deleteTask(id) {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction([STORE_NAME], 'readwrite');
    const objectStore = transaction.objectStore(STORE_NAME);
    
    const getRequest = objectStore.get(id);
    
    getRequest.onsuccess = function() {
      const task = getRequest.result;
      if (task) {
        task.status = 'completed';
        const putRequest = objectStore.put(task);
        
        putRequest.onsuccess = function() {
          resolve(task);
        };
        
        putRequest.onerror = function(event) {
          reject(event.target.error);
        };
      } else {
        reject(new Error('任务不存在'));
      }
    };
    
    getRequest.onerror = function(event) {
      reject(event.target.error);
    };
  });
}

// 物理删除任务
function physicalDeleteTask(id) {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction([STORE_NAME], 'readwrite');
    const objectStore = transaction.objectStore(STORE_NAME);
    
    const deleteRequest = objectStore.delete(id);
    
    deleteRequest.onsuccess = function() {
      resolve();
    };
    
    deleteRequest.onerror = function(event) {
      reject(event.target.error);
    };
  });
}

// 更新任务象限
function updateTaskQuadrant(id, quadrant) {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction([STORE_NAME], 'readwrite');
    const objectStore = transaction.objectStore(STORE_NAME);
    
    const getRequest = objectStore.get(id);
    
    getRequest.onsuccess = function() {
      const task = getRequest.result;
      task.quadrant = quadrant;
      
      const putRequest = objectStore.put(task);
      
      putRequest.onsuccess = function() {
        resolve(task);
      };
      
      putRequest.onerror = function(event) {
        reject(event.target.error);
      };
    };
    
    getRequest.onerror = function(event) {
      reject(event.target.error);
    };
  });
}

// 更新任务状态（仅更新任务状态，不改变任务象限 active 、 completed ）
function updateTaskStatus(id, status) {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction([STORE_NAME], 'readwrite');
    const objectStore = transaction.objectStore(STORE_NAME);
    
    const getRequest = objectStore.get(id);
    
    getRequest.onsuccess = function() {
      const task = getRequest.result;
      task.status = status;
      
      const putRequest = objectStore.put(task);
      
      putRequest.onsuccess = function() {
        resolve(task);
      };
      
      putRequest.onerror = function(event) {
        reject(event.target.error);
      };
    };
    
    getRequest.onerror = function(event) {
      reject(event.target.error);
    };
  });
}

// 计算时间距离的函数
function getTimeDistance(deadline) {
  const now = new Date();
  const deadlineDate = new Date(deadline);
  const diffMs = deadlineDate - now;
  
  if (diffMs < 0) {
    return {
      text: '',
      isExpired: true
    };
  }
  
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  const diffHours = Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const diffMinutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
  
  if (diffDays > 0) {
    return {
      text: `${diffDays}天${diffHours}小时后`,
      isExpired: false
    };
  } else if (diffHours > 0) {
    return {
      text: `${diffHours}小时${diffMinutes}分钟后`,
      isExpired: false
    };
  } else {
    return {
      text: `${diffMinutes}分钟内`,
      isExpired: false
    };
  }
}

// 渲染任务到指定象限
function renderTask(task) {
  const tasksContainer = document.getElementById(`tasks-${task.quadrant}`);
  const taskElement = document.createElement('div');
  taskElement.className = 'task-item';
  taskElement.draggable = true;
  taskElement.dataset.id = task.id;
  taskElement.dataset.quadrant = task.quadrant;
  
  // 格式化日期显示
  const deadlineDate = new Date(task.deadline);
  const formattedDeadline = deadlineDate.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
  
  // 计算时间距离
  const timeDistanceInfo = getTimeDistance(task.deadline);
  const timeDistanceClass = timeDistanceInfo.isExpired ? 'task-time-distance expired' : 'task-time-distance active';
  
  // 根据任务状态设置样式
  const taskClass = task.status === 'completed' ? 'task-item completed' : 'task-item';
  
  taskElement.innerHTML = `
    <div class="task-content">
      <div class="task-name">${task.name}</div>
      <div class="task-deadline">${formattedDeadline}</div>
      <div class="${timeDistanceClass}">${timeDistanceInfo.text}</div>
    </div>
    <div class="task-actions">
      <button class="complete-btn" data-id="${task.id}" title="完成">&#10003;</button>
      <button class="edit-btn" data-id="${task.id}" title="编辑">&#9998;</button>
    </div>
  `;
  
  taskElement.className = taskClass;
  
  tasksContainer.appendChild(taskElement);
  
  // 绑定编辑按钮事件
  taskElement.querySelector('.edit-btn').addEventListener('click', function() {
    const taskId = parseInt(this.dataset.id);
    editTask(taskId);
  });
  
  // 绑定完成按钮事件
  taskElement.querySelector('.complete-btn').addEventListener('click', function() {
    const taskId = parseInt(this.dataset.id);
    updateTaskStatus(taskId, 'completed').then(updatedTask => {
      // 重新加载任务显示
      loadAndDisplayTasks();
      // 显示已完成任务列表
      displayCompletedTasks();
    }).catch(error => {
      console.error('更新任务状态失败:', error);
    });
  });
  
  // 绑定拖拽事件
  taskElement.addEventListener('dragstart', handleDragStart);
}

// 清空所有象限的任务显示
function clearAllTasks() {
  for (let i = 1; i <= 4; i++) {
    document.getElementById(`tasks-${i}`).innerHTML = '';
  }
}

// 更新象限任务数量显示
function updateQuadrantCounts(tasks) {
  // 初始化各象限任务计数
  const counts = {1: 0, 2: 0, 3: 0, 4: 0};
  
  // 统计各象限活跃任务数量
  tasks.forEach(task => {
    if (task.status !== 'completed') {
      counts[task.quadrant]++;
    }
  });
  
  // 计算总任务数
  const totalCount = Object.values(counts).reduce((sum, count) => sum + count, 0);
  
  // 更新页面显示
  for (let i = 1; i <= 4; i++) {
    // 更新任务数量显示
    const countElement = document.getElementById(`quadrant-${i}-count`);
    if (countElement) {
      countElement.textContent = `(${counts[i]})`;
    }
    
    // 更新任务占比显示
    const percentageElement = document.getElementById(`percentage-${i}`);
    if (percentageElement) {
      if (totalCount > 0) {
        const percentage = Math.round((counts[i] / totalCount) * 100);
        percentageElement.textContent = `${percentage}%`;
      } else {
        percentageElement.textContent = '0%';
      }
    }
  }
}

// 加载并显示所有任务
function loadAndDisplayTasks() {
  clearAllTasks();
  getAllTasks().then(tasks => {
    tasks.sort((a, b) => new Date(b.deadline) - new Date(a.deadline));
    tasks.forEach(task => {
      // 只显示活跃状态的任务
      if (task.status !== 'completed') {
        renderTask(task);
      }
    });
    // 更新象限任务数量显示
    updateQuadrantCounts(tasks);
    // 显示已完成任务列表
    displayCompletedTasks();
  }).catch(error => {
    console.error('加载任务失败:', error);
  });
}

// 显示已完成任务列表
function displayCompletedTasks() {
  const completedTasksContainer = document.querySelector('.task-success-list');
  completedTasksContainer.innerHTML = '<div id="completed-tasks-container"></div>';
  
  const completedTasksList = document.getElementById('completed-tasks-container');
  
  getAllTasks().then(tasks => {
    // 过滤出已完成的任务
    const completedTasks = tasks
      .filter(task => task.status === 'completed')
      .sort((a, b) => new Date(b.deadline) - new Date(a.deadline));
    
    if (completedTasks.length === 0) {
      completedTasksList.innerHTML = '<p>暂无内容</p>';
      return;
    }
    
    completedTasks.forEach(task => {
      const taskElement = document.createElement('div');
      taskElement.className = 'completed-task-item';
      
      // 格式化日期显示
      const deadlineDate = new Date(task.deadline);
      const formattedDeadline = deadlineDate.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
      
      // 计算时间距离
      const timeDistanceInfo = getTimeDistance(task.deadline);
      const timeDistanceClass = timeDistanceInfo.isExpired ? 'task-time-distance expired' : 'task-time-distance active';
      
      taskElement.innerHTML = `
        <div class="task-content">
          <div class="task-name" title="${task.name}">${task.name}</div>
          <div class="task-deadline">${formattedDeadline}</div>
          <div class="${timeDistanceClass}">${timeDistanceInfo.text}</div>
        </div>
        <div class="task-actions">
          <button class="restore-btn" data-id="${task.id}" title="恢复">&#8634;</button>
          <button class="delete-btn" data-id="${task.id}" title="删除">&#10060;</button>
        </div>
      `;
      
      completedTasksList.appendChild(taskElement);
      
      // 绑定恢复按钮事件
      taskElement.querySelector('.restore-btn').addEventListener('click', function() {
        const taskId = parseInt(this.dataset.id);
        updateTaskStatus(taskId, 'active').then(updatedTask => {
          // 重新加载任务显示
          loadAndDisplayTasks();
        }).catch(error => {
          console.error('恢复任务失败:', error);
        });
      });
      
      // 绑定删除按钮事件
      taskElement.querySelector('.delete-btn').addEventListener('click', function() {
        const taskId = parseInt(this.dataset.id);
        physicalDeleteTask(taskId).then(() => {
          taskElement.remove();
          // 重新加载任务显示
          loadAndDisplayTasks();
        }).catch(error => {
          console.error('删除任务失败:', error);
        });
      });
    });
  }).catch(error => {
    console.error('加载已完成任务失败:', error);
  });
}

// 拖拽开始事件
function handleDragStart(e) {
  e.dataTransfer.setData('text/plain', e.target.dataset.id);
  e.dataTransfer.effectAllowed = 'move';
}

// 拖拽放置事件
function handleDragOver(e) {
  e.preventDefault();
  e.dataTransfer.dropEffect = 'move';
}

// 拖拽放置事件
function handleDrop(e) {
  e.preventDefault();
  const taskId = e.dataTransfer.getData('text/plain');
  const targetQuadrant = e.currentTarget.dataset.quadrant;
  
  // 更新任务象限
  updateTaskQuadrant(parseInt(taskId), parseInt(targetQuadrant)).then(updatedTask => {
    // 重新加载任务显示
    loadAndDisplayTasks();
  }).catch(error => {
    console.error('更新任务象限失败:', error);
  });
}

// 打开任务编辑模态框
function openTaskModal(quadrant, task = null) {
  const modal = document.getElementById('task-modal');
  const title = document.getElementById('modal-title');
  const taskIdInput = document.getElementById('task-id');
  const taskQuadrantInput = document.getElementById('task-quadrant');
  const taskNameInput = document.getElementById('task-name');
  const taskDeadlineInput = document.getElementById('task-deadline');
  
  if (task) {
    // 编辑模式
    title.textContent = '编辑任务';
    taskIdInput.value = task.id;
    taskQuadrantInput.value = task.quadrant;
    taskNameInput.value = task.name;
    
    // 格式化日期为输入框所需格式
    const deadlineDate = new Date(task.deadline);
    const formattedDeadline = deadlineDate.toISOString().slice(0, 16);
    taskDeadlineInput.value = formattedDeadline;
  } else {
    // 新建模式
    title.textContent = '添加任务';
    taskIdInput.value = '';
    taskQuadrantInput.value = quadrant;
    taskNameInput.value = '';
    // 默认截止时间为当前时间加5小时
    const defaultDeadline = new Date(Date.now() + 13 * 60 * 60 * 1000);
    taskDeadlineInput.value = defaultDeadline.toISOString().slice(0, 16);
  }
  
  modal.style.display = 'block';
}

// 关闭任务编辑模态框
function closeTaskModal() {
  const modal = document.getElementById('task-modal');
  modal.style.display = 'none';
}

// 编辑任务
function editTask(taskId) {
  getAllTasks().then(tasks => {
    const task = tasks.find(t => t.id === taskId);
    if (task) {
      openTaskModal(task.quadrant, task);
    }
  }).catch(error => {
    console.error('获取任务失败:', error);
  });
}

// 导出所有任务为JSON文件
function exportTasks() {
  getAllTasks().then(tasks => {
    // 提示用户即将导出到默认下载目录
    const confirmExport = confirm(`系统将导出您的任务数据到默认下载目录。\n文件名：工作备忘录_导出_${new Date().toLocaleDateString('zh-CN')}.json\n\n点击"确定"继续导出。`);
    if (!confirmExport) {
      console.log('用户取消了导出');
      return;
    }
    
    // 创建要导出的数据对象
    const exportData = {
      exportDate: new Date().toISOString(),
      tasks: tasks
    };
    
    // 将数据转换为JSON字符串
    const dataStr = JSON.stringify(exportData, null, 2);
    
    // 创建Blob对象
    const blob = new Blob([dataStr], {type: 'application/json'});
    
    // 创建下载链接
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `工作备忘录_导出_${new Date().toLocaleDateString('zh-CN')}.json`;
    
    // 触发下载
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    // 释放URL对象
    URL.revokeObjectURL(url);
    
    // 提示导出成功
    alert('任务数据已成功导出到您的默认下载目录！');
  }).catch(error => {
    console.error('导出任务失败:', error);
    alert('导出任务失败，请查看控制台了解详情。');
  });
}

// 打开任务编辑模态框
function openTaskModal(quadrant, task = null) {
  const modal = document.getElementById('task-modal');
  const title = document.getElementById('modal-title');
  const taskIdInput = document.getElementById('task-id');
  const taskQuadrantInput = document.getElementById('task-quadrant');
  const taskNameInput = document.getElementById('task-name');
  const taskDeadlineInput = document.getElementById('task-deadline');
  
  if (task) {
    // 编辑模式
    title.textContent = '编辑任务';
    taskIdInput.value = task.id;
    taskQuadrantInput.value = task.quadrant;
    taskNameInput.value = task.name;
    
    // 格式化日期为输入框所需格式
    const deadlineDate = new Date(task.deadline);
    const formattedDeadline = deadlineDate.toISOString().slice(0, 16);
    taskDeadlineInput.value = formattedDeadline;
  } else {
    // 新建模式
    title.textContent = '添加任务';
    taskIdInput.value = '';
    taskQuadrantInput.value = quadrant;
    taskNameInput.value = '';
    // 默认截止时间为当前时间加5小时
    const defaultDeadline = new Date(Date.now() + 13 * 60 * 60 * 1000);
    taskDeadlineInput.value = defaultDeadline.toISOString().slice(0, 16);
  }
  
  modal.style.display = 'block';
}

// 关闭任务编辑模态框
function closeTaskModal() {
  const modal = document.getElementById('task-modal');
  modal.style.display = 'none';
}

// 编辑任务
function editTask(taskId) {
  getAllTasks().then(tasks => {
    const task = tasks.find(t => t.id === taskId);
    if (task) {
      openTaskModal(task.quadrant, task);
    }
  }).catch(error => {
    console.error('获取任务失败:', error);
  });
}

// 导出所有任务为JSON文件
function exportTasks() {
  getAllTasks().then(tasks => {
    // 创建要导出的数据对象
    const exportData = {
      exportDate: new Date().toISOString(),
      tasks: tasks
    };
    
    // 将数据转换为JSON字符串
    const dataStr = JSON.stringify(exportData, null, 2);
    
    // 创建Blob对象
    const blob = new Blob([dataStr], {type: 'application/json'});
    
    // 创建下载链接
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `工作备忘录_导出_${new Date().toLocaleDateString('zh-CN')}.json`;
    
    // 触发下载
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    // 释放URL对象
    URL.revokeObjectURL(url);
  }).catch(error => {
    console.error('导出任务失败:', error);
    alert('导出任务失败，请查看控制台了解详情。');
  });
}

// 导入任务数据
function importTasks() {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.json';
  
  input.onchange = function(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    const reader = new FileReader();
    reader.onload = function(e) {
      try {
        const importData = JSON.parse(e.target.result);
        
        // 验证导入数据格式
        if (!importData.tasks || !Array.isArray(importData.tasks)) {
          throw new Error('无效的数据格式');
        }
        
        // 确认是否要导入数据（这会覆盖现有数据）
        const confirmImport = confirm(`检测到${importData.tasks.length}个任务，确定要导入吗？这将覆盖当前的所有数据！`);
        if (!confirmImport) return;
        
        // 清空现有数据
        clearAllData().then(() => {
          // 导入数据
          const importPromises = importData.tasks.map(task => {
            // 重新生成ID以避免冲突
            delete task.id;
            return saveTask(task);
          });
          
          Promise.all(importPromises).then(() => {
            // 重新加载任务显示
            loadAndDisplayTasks();
            alert(`成功导入${importData.tasks.length}个任务！`);
          }).catch(error => {
            console.error('导入任务失败:', error);
            alert('导入任务失败，请查看控制台了解详情。');
          });
        }).catch(error => {
          console.error('清空数据失败:', error);
          alert('导入失败：无法清空现有数据');
        });
      } catch (error) {
        console.error('解析导入文件失败:', error);
        alert('导入失败：文件格式不正确');
      }
    };
    
    reader.readAsText(file);
  };
  
  input.click();
}

// 清空所有数据
function clearAllData() {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction([STORE_NAME], 'readwrite');
    const objectStore = transaction.objectStore(STORE_NAME);
    
    const request = objectStore.clear();
    
    request.onsuccess = function() {
      resolve();
    };
    
    request.onerror = function(event) {
      reject(event.target.error);
    };
  });
}

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
  // 初始化数据库
  initDB().then(() => {
    // 加载并显示所有任务
    loadAndDisplayTasks();
    
    // 更新最后备份时间显示
    updateLastBackupTime();
    
    // 启动自动导出功能
    startAutoExport();
    
    // 绑定添加任务按钮事件
    document.querySelectorAll('.add-task-btn').forEach(button => {
      button.addEventListener('click', function() {
        const quadrant = this.dataset.quadrant;
        openTaskModal(quadrant);
      });
    });
    
    // 绑定模态框关闭事件
    document.querySelector('.close').addEventListener('click', closeTaskModal);
    window.addEventListener('click', function(event) {
      const modal = document.getElementById('task-modal');
      if (event.target === modal) {
        closeTaskModal();
      }
    });
    
    // 绑定表单提交事件
    document.getElementById('task-form').addEventListener('submit', function(e) {
      e.preventDefault();
      
      const taskId = document.getElementById('task-id').value;
      const quadrant = document.getElementById('task-quadrant').value;
      const name = document.getElementById('task-name').value;
      const deadline = document.getElementById('task-deadline').value;

      if (!name || !deadline) {
        alert('请填写任务名称和截止时间');
        return;
      }
      
      const task = {
        name: name,
        deadline: new Date(deadline).toISOString(),
        quadrant: parseInt(quadrant),
        status: 'active' // 默认状态为活跃
      };
      
      if (taskId) {
        task.id = parseInt(taskId);
      }
      
      saveTask(task).then(savedTask => {
        closeTaskModal();
        loadAndDisplayTasks();
      }).catch(error => {
        console.error('保存任务失败:', error);
      });
    });
    
    // 绑定拖拽放置事件到各个象限
    document.querySelectorAll('.quadrant').forEach(quadrant => {
      quadrant.addEventListener('dragover', handleDragOver);
      quadrant.addEventListener('drop', handleDrop);
    });
    
    // 绑定导出按钮事件
    const exportBtn = document.querySelector('.export-btn');
    if (exportBtn) {
      exportBtn.addEventListener('click', function(e) {
        e.preventDefault();
        exportTasks();
      });
    }
    
    // 绑定导入按钮事件
    const importBtn = document.querySelector('.import-btn');
    if (importBtn) {
      importBtn.addEventListener('click', function(e) {
        e.preventDefault();
        importTasks();
      });
    }
  }).catch(error => {
    console.error('初始化数据库失败:', error);
  });
});


// 自动导出任务数据（每天导出一次）
function autoExportTasks() {
  const lastExportKey = 'lastAutoExport';
  const now = new Date().getTime();
  const lastExport = localStorage.getItem(lastExportKey);
  
  // 如果从未导出过，或者距离上次导出已经超过24小时，则自动导出
  if (!lastExport || (now - parseInt(lastExport)) > 7 * 24 * 60 * 60 * 1000) {
    getAllTasks().then(tasks => {
      // 只有当有任务时才导出
      if (tasks.length > 0) {
        // 创建要导出的数据对象
        const exportData = {
          exportDate: new Date().toISOString(),
          autoExport: true,
          tasks: tasks
        };
        
        // 将数据转换为JSON字符串
        const dataStr = JSON.stringify(exportData, null, 2);
        
        // 创建Blob对象
        const blob = new Blob([dataStr], {type: 'application/json'});
        
        // 创建下载链接
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `工作备忘录_自动导出_${new Date().toLocaleDateString('zh-CN')}.json`;
        
        // 触发下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // 释放URL对象
        URL.revokeObjectURL(url);
        
        // 记录导出时间
        localStorage.setItem(lastExportKey, now.toString());
        
        // 更新页面上的最后备份时间显示
        updateLastBackupTime();
        
        console.log('自动导出完成');
      }
    }).catch(error => {
      console.error('自动导出任务失败:', error);
    });
  }
}

// 更新最后备份时间显示
function updateLastBackupTime() {
  const lastExportKey = 'lastAutoExport';
  const lastExport = localStorage.getItem(lastExportKey);
  const lastBackupLabel = document.querySelector('.last-bak-data');
  
  if (lastBackupLabel) {
    if (lastExport) {
      const backupTime = new Date(parseInt(lastExport));
      const formattedTime = backupTime.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
      lastBackupLabel.textContent = `最后备份：${formattedTime}`;
    } else {
      lastBackupLabel.textContent = '最后备份：暂无备份';
    }
  }
}

// 启动自动导出检查
function startAutoExport() {
  // 页面加载时检查一次
  autoExportTasks();
  
  // 每小时检查一次是否需要自动导出
  setInterval(autoExportTasks, 60 * 1000);
}